package com.vipboot.platform.system.framework;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt;
import com.vipboot.framework.core.util.ObjectUtil;
import com.vipboot.framework.core.util.StringConst;
import com.vipboot.framework.core.util.StringUtil;
import com.vipboot.framework.translation.annotation.TranslationType;
import com.vipboot.framework.translation.constant.TransConst;
import com.vipboot.framework.translation.core.TranslationInterface;
import com.vipboot.platform.system.crud.dao.SysDeptDao;
import com.vipboot.platform.system.domain.entity.SysDept;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@AllArgsConstructor
@TranslationType(type = TransConst.DeptIdToName)
public class DeptNameTranslationImpl implements TranslationInterface<String> {

    private final SysDeptDao sysDeptDao;

    @Override
    public String translation(Object key, String other) {
        if (key instanceof String ids) {
            return this.selectDeptNameByIds(ids);
        } else if (key instanceof Long id) {
            return this.selectDeptNameByIds(id.toString());
        }
        return null;
    }

    private String selectDeptNameByIds(String deptIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtil.splitTo(deptIds, Convert::toLong)) {
            String deptName = Opt.ofNullable(sysDeptDao.getById(id))
                    .map(SysDept::getDeptName)
                    .orElse(StringConst.EMPTY);
            if (ObjectUtil.isNotEmpty(deptName)) {
                list.add(deptName);
            }
        }
        return String.join(StringUtil.SEPARATOR, list);
    }
}
